package com.niuwa.p2p.action.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;

import com.niuwa.p2p.action.JsonAction;
import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.mvc.entity.Pagination;
import com.niuwa.p2p.entity.resource.Resource;
import com.niuwa.p2p.entity.role.Role;
import com.niuwa.p2p.entity.user.User;
import com.niuwa.p2p.service.resource.ResourcesService;
import com.niuwa.p2p.service.role.RoleService;
import com.niuwa.p2p.service.user.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
/**
 * 
 * @ClassName: UserAction
 * @Descriptio 用户Action
 * @author:    jishengjun
 * 
 */

public class UserAction extends JsonAction implements ModelDriven<Object>{

	private static final long serialVersionUID = -8900124777631535966L;

	/** 日志 */
	private static Logger logger = Logger.getLogger(UserAction.class);
	private String message;
	/** 用户Servcie spring扫包注入 */
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public ResourcesService getResourcesService() {
		return resourcesService;
	}

	public void setResourceService(ResourcesService resourcesService) {
		this.resourcesService = resourcesService;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	//资源Service spring扫包注入 /
	@Autowired
	private ResourcesService resourcesService;
	
	/** 用户  */
	private User user;
	
	
	//登入用户名
	private  String j_userName;
	
	private String j_password;
	
	
	

	public String getJ_userName() {
		return j_userName;
	}

	public void setJ_userName(String j_userName) {
		this.j_userName = j_userName;
	}

	public String getJ_password() {
		return j_password;
	}

	public void setJ_password(String j_password) {
		this.j_password = j_password;
	}

	public void setResourcesService(ResourcesService resourcesService) {
		this.resourcesService = resourcesService;
	}

	/** 用户编辑的逻辑符号
    *   add：   添加
    *   edit：编辑
    *   del：   删除
    */
	private String oper = "";
	
	
	//资源号
	private  String number;

	public UserService getUserService() {
		return userService;
	}
	
	
	
 	
	/**
	 * 个人用户修改界面迁移
	 * 
	 * @return 
	 */
	@SkipValidation
	@Action("gotoUserUpdate")
	public String gotoUserUpdate() throws Exception {
		
		// TODO del 得到用户登录名 
		User newUser = userService.getUser(1);
		ActionContext.getContext().getSession().put("currentUser", newUser);
					
		User currentUser = (User) ActionContext.getContext().getSession().get("currentUser");	
		
		// 根据登录名更新
		user = userService.getUser(currentUser.getLoginName());
		logger.info("gotoUserUpdate");

		return "userUpdate";
	}
	
	/**
	 * 保存个人用户
	 * 
	 * @return SUCCESS:用户信息确认画面 
	 * @throws Exception 
	 */	
	@Action("updateUser")
			//results={@Result(location="userManager.jsp", name=SUCCESS),@Result(location="userUpdate.jsp", name=INPUT)})
	/*@Validations(requiredStrings = {
		    @RequiredStringValidator(fieldName = "user.userName", type = ValidatorType.FIELD, message ="${getText(\"user.userName.RequiredString.message\")}"),
			@RequiredStringValidator(fieldName = "user.loginPassword", type = ValidatorType.FIELD, message = "${getText(\"user.loginPassword.RequiredString.message\")}")},
			stringLengthFields = {
	        @StringLengthFieldValidator(fieldName = "user.userName", type = ValidatorType.FIELD, maxLength = "30",message = "${getText(\"user.loginPassword.RequiredString.message \")}"),
	        @StringLengthFieldValidator(fieldName = "user.loginPassword", type = ValidatorType.FIELD, minLength = "6", maxLength = "20",message = "${getText(\"user.loginPassword.StringLength.message\")}")},
	        regexFields={@RegexFieldValidator(fieldName="user.tel",  type = ValidatorType.FIELD, regexExpression="${getText(\"user.tel.regex.expression\")}", message="${getText(\"user.tel.regex.message\")}")},
			emails = {
					@EmailValidator(fieldName = "user.email", type = ValidatorType.FIELD, message = "${getText(\"user.emails.emails.message\")}")})*/
	public String updateUser() throws Exception {					
			JsonResult  results=new JsonResult();
			try {
				// 得到当前用户
				User currentUser = (User) ActionContext.getContext().getSession().get("user");		

				// 更新用户信息
				userService.updateUser(user,currentUser.getLoginName());
				results.setMsg("修改成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				results.setMsg("修改失败");
				e.printStackTrace();
			}finally{
				
				setResult(results);
			}
		return NONE;
	}

	
	
	/**
	 * 
	 *删除用户
	 * @return
	 * @throws Exception
	 *
	 */
	@Action("userDelete")
	public String deleteUser() throws Exception {					
		JsonResult  results=new JsonResult();
		try {
			// 更新用户信息
			userService.deleteUser(user);
			results.setMsg("删除成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			results.setMsg("删除失败");
			e.printStackTrace();
		}finally{
			
			setResult(results);
		}
	return NONE;
}
	
	/**
	 * 跳转到用户管理画面
	 * 
	 * @return userManager 用户管理画面
	 */
	@SkipValidation
	@Action("gotoUserManager")
	public String gotoUserManager() {


		logger.info("goto UserManager page.");

		return "userManager";
	}	
	
	/**
	 * 
	 * 跳转到用户增加页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "gotoAddUserPage")
	public String gotoAddRolePage()  {
	
		return "addUserPage";
	}
	
	

	
	/**
	 * 
	 * 跳转到用户修改页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "gotoUpdateUserPage")
	public String gotoUpdateUserPage()  {
	
		return "updateUserPage";
		
	}
	
	

	
	/**
	 * 跳转到用户管理画面
	 * 
	 * @return userManager 用户管理画面
	 */
	@SkipValidation
	@Action("systemManager")
	public String systemManager() {


		logger.info("goto UserManager page.");
		return "systemManager";
	}	
	/**
	 * 选择用户集合并转换为Json，传递给Client
	 * 
	 * @return NONE 返回当页
	 */
	@SkipValidation
	@Action(value="userGridDataProvider", 
		results={@Result(location="userManager.jsp", name=SUCCESS),@Result(location="userManager.jsp", name=INPUT)})
	public String userGridDataProvider() {
		logger.debug("UserAction.userGridDataProvider loadGridData");
		reLoadGridData();
		return NONE;
	}

	/**
	 * 跳转到用户管理画面
	 * 
	 * @return userManager 用户管理画面
	 */
	@SkipValidation
	@Action("gotoUserLogin")
	public String gotoUserLogin() {
		logger.info("goto gotoUserLogin page.");
		return "login";
	}	
	
	
	/**
	 * 
	 *登入主页面,判断用户名和密码。
	 *@param
	 *@rerurn  
	 * @return
	 *
	 */
    @Action(value="goToIndexPage", results={@org.apache.struts2.convention.annotation.Result(location="../goToIndexPage.jsp", name="success"),@Result(name=INPUT,location="../login.jsp")})
//	@Validations(requiredStrings = { 
//	        @com.opensymphony.xwork2.validator.annotations.RequiredStringValidator(fieldName = "j_username", message = "${getText(\"user.loginName.RequiredString.message\")}"),
//	        @com.opensymphony.xwork2.validator.annotations.RequiredStringValidator(fieldName = "j_password", message = "${getText(\"user.loginPassword.RequiredString.message\")}")},
//	    stringLengthFields = {
//	        @com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator(fieldName = "j_password", minLength = "6", maxLength = "20", message = "密码长度只允许为6-20!")})
	public String goToIndexPage() {
	HttpServletRequest request=ServletActionContext.getRequest();
	HttpServletResponse response=ServletActionContext.getResponse();
	UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
    String password=	userDetails.getPassword();
    String loginName=userDetails.getUsername();
	HttpSession session=request.getSession();
	User user = userService.getUser(loginName, password);
	if(user==null){
		request.setAttribute("errorMessage", "用户名或密码不正确！");
		return INPUT;
	}else{
	   HashMap<String,String> paramMap=new HashMap<String, String>();
		paramMap.put("loginName", loginName);
		paramMap.put("password", password);
		List<Resource> resources = resourcesService.searchResourcesByUserInfo(paramMap);
		List<Resource>  authResources = resourcesService.searchAuthResourcesByUserInfo(paramMap);
		List<Role> roleList=roleService.searchRolesByloginName(loginName);
		List<Resource> resourceList = getDistinctResource(resources);	
		List<Resource> AuthResourceList = getDistinctResource(authResources);	
		//Map<String,List<Resource>>  resourceMap=getResourceMap(resourceList); 
		//JSONObject  resourcesJson2 =JSONObject.fromObject(resourceMap);
		JSONArray rolesJson =JSONArray.fromObject(roleList);
		JSONArray  resourcesJson=JSONArray.fromObject(resourceList );
		JSONArray  AuthResourcesJson=JSONArray.fromObject(AuthResourceList);
		Random random = new Random();  
		StringBuffer sid = new StringBuffer();  
		sid = sid.append(System.currentTimeMillis());   //  取系统时间  
		//  加上10为0-9随机数确保sid不重复  
		for (int i = 0; i < 100; i++) {  
		    sid = sid.append(random.nextInt(100));  
		}  
		  
		//  把所有需要放进session的attribute放进一个Mapbar<String, Object>  
		//  一是便于el中取值、二是便于统一管理  
		Map<String,Object> sessionMap = new HashMap<String,Object>();  
		sessionMap.put("user", user); 
		sessionMap.put("resource",resourceList);  
		sessionMap.put("rolesJson", rolesJson);  
		sessionMap.put("resourcesJson", resourcesJson);  
		sessionMap.put("AuthResourcesJson", AuthResourcesJson);  
		session.setAttribute(sid.toString(), sessionMap);   
		session.setAttribute("user", user);   
		session.setAttribute("resource",resourceList);   
		String rd = "/WEB-INF/content/goToIndexPage.jsp?sid=" + sid.toString();  
		try {
			request.getRequestDispatcher(rd).forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
		return NONE;
	}
	
	
	
	@Action(value="/login",  results={@Result(name = SUCCESS, location = "/login.jsp")})
	public String login() {
		return SUCCESS;
	}	
	
	/**
	 * 
	 *退出页面
	 * @return
	 *
	 */
	@Action(value="logout",  results={@Result(name = SUCCESS, location = "/login.jsp")})
	public String logout() {
	Map<String,Object> session=ActionContext.getContext().getSession();
		session.clear();
		return SUCCESS;
	}	
	
	
	/**
	 * 用户列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "userList")
	public String userList() throws Exception {
		setObjectReSult(queryPage());
		logger.info("userList action execute success");
		return NONE;
	}

	/**
	 * 用户操作：添加，更新，删除
	 * 
	 * @return NONE 返回当页
	 */
	@SkipValidation
	@Action(value="userEditGridEntry", 
			results={@Result(location="userManager.jsp", name=SUCCESS),@Result(location="userManager.jsp", name=INPUT)})
	public String userEditGridEntry() throws Exception {
		userService.editUser(getModel(), oper);		
	   return NONE;
	}
		
	/**
	 * 分页查询
	 * 
	 * @return Pagination<User> 分页信息与分页数据集合（用户集合） 
	 */
	private PageBean<User> queryPage() {

		// 获取查询参数
		Map<String, Object> paramMap = getParamMap();

		// 查选分页集合
		PageBean<User> page = userService.search(paramMap);
		
		return page;
	}
	
	
	/**
	 * 用户新增
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addUser")
	public String addUser() throws Exception {
	              String currentLoginName=   UserAction.getSessionUser().getLoginName();  
	             String message=new String();
	              JsonResult results=new JsonResult();
		try {
			List<User> userList=userService.searchUserByloginName(user);
			 if(userList.size()!=0){
				 message="登入名重复,新增失败";
				 throw new RuntimeException();
			 }else{
				 userService.addUser(user,currentLoginName); 
				 message="新增成功";
				 results.setMsg(message);
				 setResult(results);
			 }
		} catch (Exception e) {
			if(!("登入名重复,新增失败".equalsIgnoreCase(message))){
			   message="新增失败";
			}
			 results.setMsg(message);
			  setResult(results);
			  e.printStackTrace();	
		}
		return NONE;            
		
	}
	
	
	private List<Resource> getDistinctResource(List<Resource> resources) {
		List<Resource> resourceList = new ArrayList<Resource>();
		for (Resource resource : resources) {
			if (!resourceList.contains(resource)) {
				resourceList.add(resource);
			}
		}
		return resourceList;

	}

	/**
	 * 重新载入用户页面数据 
	 */
	private void reLoadGridData(){
		
		// 分页查询集合存入JsonResult
		JsonResult jsonResult = new JsonResult(queryPage());
		setResult(jsonResult);

	}
	
	
	
	/**
	 * TODO 转入共通
	 * 判断字符串是否为空 
	 *  
	 */
	private boolean isEmpty(String s){
		return null == s || "".equals(s.trim());
	}
	
	/**
	 * TODO 转入共通
	 * 判断字符串是否不为空 
	 *  
	 */
	private boolean isNotempty(String s){
		return !isEmpty(s);
	}
	
	/**
	 * ModelDriven的接口方法实现
	 * 取得Cilent表单参数，分装到用户Bean
	 * 
	 * @return 用户
	 */
	
	
	public User getModel() {
		  if (null == user) {
		   return user = new User();
		  }
		  return user;
	}
	
	public static User getSessionUser(){
		 HttpSession  session=ServletActionContext.getRequest().getSession();
		 User user=(User)session.getAttribute("user");
		 return user;
	}
	
	/**
	 * 
	 *返回前台资源
	 * @param resourceList
	 * @return  resourceMap
	 *
	 */
	public Map<String,List<Resource>>  getResourceMap(List<Resource> resourceList){
		String rootReourceNo="no_8";
		Map<String,List<Resource>>  resourceMap=new HashMap<String, List<Resource>>();
		if(resourceList!=null&&resourceList.size()!=0){
			for(int i=0;i<resourceList.size();i++){
				List<Resource> resourceChildrenList=new ArrayList<Resource>();
				for(int j=0;j<resourceList.size();j++){
					if(resourceList.get(i).getNumber().equals(resourceList.get(j).getPid())){
						resourceChildrenList.add(resourceList.get(j));
					}		
				}
				if(resourceChildrenList!=null&&resourceChildrenList.size()!=0){
					 resourceMap.put(resourceList.get(i).getNumber(), resourceChildrenList);
				}
			}
		}
		List<Resource>resourceList2=resourceMap.get(rootReourceNo);
		if(resourceList2!=null&&resourceList2.size()!=0){
			 resourceMap.remove(rootReourceNo);
			 resourceMap.put("root", resourceList2);
		}
		return  resourceMap;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public String getOper() {
		return oper;
	}

	public void setOper(String oper) {
		this.oper = oper;
	}
	
}
